/**
 * 类名：MessageAction
 * 创建日期： 2014-11-7 下午2:48:46
 * 
 */
package com.erms.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jms.Session;
import javax.security.auth.message.callback.PrivateKeyCallback.Request;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.erms.bean.Courseware;
import com.erms.bean.FileInfo;
import com.erms.bean.Message;
import com.erms.bean.StudentTeach;
import com.erms.bean.Teach;
import com.erms.bean.User;
import com.erms.dao.MessageDAO;
import com.erms.dao.StudentTeachDAO;
import com.erms.dao.TeachDAO;
import com.erms.dao.UserDAO;
import com.erms.domain.MessageService;
import com.erms.util.StringUtil;
import com.erms.util.TimeUtil;

/**
 * @author gwj 备注：
 * 
 */
public class MessageAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -9069031770187290641L;

	private MessageDAO messageDAO;
	private UserDAO userDAO;
	private StudentTeachDAO studentTeachDAO;
	private TeachDAO teachDAO;
	private User user;
	private Integer pageCount;
	private Integer pageNum = 1;
	private List<Message> messageList;
	private String order = "timeInc";
	private String messageJson;
	private String teachJson;
	private String title;
	private String content;
	private String newFileName;
	private String teachID;
	private File upload;
	private String uploadContentType;
	private String uploadFileName;
	private MessageService messageService;

	public MessageService getMessageService() {
		return messageService;
	}

	public void setMessageService(MessageService messageService) {
		this.messageService = messageService;
	}

	// 作为json返回结果
	private String jsonResult = "";

	public TeachDAO getTeachDAO() {
		return teachDAO;
	}

	public void setTeachDAO(TeachDAO teachDAO) {
		this.teachDAO = teachDAO;
	}

	public MessageDAO getMessageDAO() {
		return messageDAO;
	}

	public void setMessageDAO(MessageDAO messageDAO) {
		this.messageDAO = messageDAO;
	}

	public Integer getPageCount() {
		return pageCount;
	}

	public void setPageCount(Integer pageCount) {
		this.pageCount = pageCount;
	}

	public Integer getPageNum() {
		return pageNum;
	}

	public void setPageNum(Integer pageNum) {
		this.pageNum = pageNum;
	}

	public List<Message> getMessageList() {
		return messageList;
	}

	public void setMessageList(List<Message> messageList) {
		this.messageList = messageList;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		String userID = (String) getSession().getAttribute(KEY_USERNAME);
		if (StringUtil.isNull(userID)) {
			return LOGIN;
		}
		if (TEACHER.equals(getSession().getAttribute(KEY_TYPE)))
			pre_teachJson();
		pre_messageJson();
		return super.execute();
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public User getUser() {
		user = userDAO.findById((String) getSession().getAttribute("username"));
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public StudentTeachDAO getStudentTeachDAO() {
		return studentTeachDAO;
	}

	public void setStudentTeachDAO(StudentTeachDAO studentTeachDAO) {
		this.studentTeachDAO = studentTeachDAO;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public String getMessageJson() {
		return messageJson;
	}

	public void setMessageJson(String messageJson) {
		this.messageJson = messageJson;
	}

	@SuppressWarnings("unchecked")
	private void pre_messageJson() {
		List<Message> allMessageList = new ArrayList<>();
		messageList = new ArrayList<>();
		String username = (String) getSession().getAttribute(KEY_USERNAME);
		String typeString = (String) getSession().getAttribute(KEY_TYPE);
		int len = 0;
		if (STUDENT.equals(typeString)) {
			List<StudentTeach> tempList = studentTeachDAO.findByStuID(username);
			int size = tempList.size();
			for (int i = 0; i < size; i++) {
				allMessageList.addAll(messageDAO.findByTeachID(tempList.get(i)
						.getId().getTeach().getId()));
			}
		} else if (TEACHER.equals(typeString)) {
			// List tempList = studentTeachDAO.findByTeachID(username);
			// int size = tempList.size();
			// for (int i = 0; i < size; i++) {
			// allMessageList.addAll(messageDAO
			// .findByTeachID(((StudentTeach) tempList.get(i)).getId()
			// .getTeach().getId()));
			// }
			logger.debug("\n\n\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!");
			List<Teach> teachList = teachDAO.findByTeacherId(username);
			int size = teachList.size();
			for (int i = 0; i < size; i++) {
				allMessageList.addAll(messageDAO.findByTeachID(teachList.get(i)
						.getId()));
			}
			logger.debug("\n\n\n\n" + allMessageList.size());
		}
		if ("timeInc".equals(order)) {
			Collections.sort(allMessageList, new Comparator<Message>() {
				@Override
				public int compare(Message o1, Message o2) {
					// TODO Auto-generated method stub
					return o1.getTime().compareTo(o2.getTime());
				}
			});
		} else if ("timeDec".equals(order)) {
			Collections.sort(allMessageList, new Comparator<Message>() {
				@Override
				public int compare(Message o1, Message o2) {
					// TODO Auto-generated method stub
					return o2.getTime().compareTo(o1.getTime());
				}
			});
		} else if ("tachInc".equals(order)) {
			Collections.sort(allMessageList, new Comparator<Message>() {
				@Override
				public int compare(Message o1, Message o2) {
					// TODO Auto-generated method stub
					return o1.getTeach().getId()
							.compareTo(o2.getTeach().getId());
				}
			});
		} else if ("tachDec".equals(order)) {
			Collections.sort(allMessageList, new Comparator<Message>() {
				@Override
				public int compare(Message o1, Message o2) {
					// TODO Auto-generated method stub
					return o2.getTeach().getId()
							.compareTo(o1.getTeach().getId());
				}
			});
		}
		len = allMessageList.size();
		pageCount = (len % 5 == 0) ? (len / 5) : (len / 5 + 1);
		if (pageCount == 0)
			pageCount = 1;
		if (pageNum >= 1 && pageNum <= pageCount) {
			messageList.addAll(allMessageList.subList((pageNum - 1) * 5,
					(pageNum * 5 <= len) ? (pageNum * 5) : len));
		}
		List<Map<String, String>> listToJsonList = new ArrayList<>();
		for (Message message : messageList) {
			listToJsonList.add(getMessageMap(message));
		}
		setMessageJson(JSONArray.fromObject(listToJsonList).toString());
	}

	public Map<String, String> getMessageMap(Message message) {
		Map<String, String> map = new HashMap<>();
		map.put("messageID", message.getId().toString());
		if (message.getTitle() == null) {
			map.put("title", "空");
		} else {
			map.put("title", message.getTitle());
		}
		if (message.getContent() == null) {
			map.put("content", "空");
		} else {
			map.put("content", message.getContent());
		}
		if (message.getFileInfo() == null) {
			map.put("file", "无");
			map.put("id", "-1");
		} else {
			String fullName = message.getFileInfo().getName();
			int a = fullName.lastIndexOf("_");
			int b = fullName.lastIndexOf(".");
			if (a != -1 && b != -1) {
				map.put("file",
						fullName.substring(0, a) + fullName.substring(b));
			} else {
				map.put("file", fullName);
			}
			map.put("id", message.getFileInfo().getId().toString());
		}
		map.put("course", message.getTeach().getCourse().getName());
		map.put("time", TimeUtil.format(message.getTime()));
		return map;
	}

	public String getTeachJson() {
		return teachJson;
	}

	public void setTeachJson(String teachJson) {
		this.teachJson = teachJson;
	}

	public void pre_teachJson() {
		String userID = (String) getSession().getAttribute(KEY_USERNAME);
		@SuppressWarnings("unchecked")
		List<Teach> teachs = teachDAO.findByTeacherId(userID);
		List<Map<String, String>> teachList = new ArrayList<>();
		int n = teachs.size();
		for (int i = 0; i < n; i++) {
			Teach teach = teachs.get(i);
			Map<String, String> map = new HashMap<String, String>();
			String courseName = teach.getCourse().getName();
			map.put("id", teach.getId());
			map.put("name", courseName);
			teachList.add(map);
		}
		teachJson = JSONArray.fromObject(teachList).toString();
	}

	public String upload() {

		logger.debug(uploadFileName + "\n\n\n");

		String userID = (String) getSession().getAttribute(KEY_USERNAME);
		if (StringUtil.isNull(userID)) {
			return LOGIN;
		}

		if (messageService.save(title, content, teachID, upload,
				uploadFileName, uploadContentType, newFileName, null, userID)) {
			return SUCCESS;
		} else {
			return ERROR;
		}
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getNewFileName() {
		return newFileName;
	}

	public void setNewFileName(String newFileName) {
		this.newFileName = newFileName;
	}

	public String getTeachID() {
		return teachID;
	}

	public void setTeachID(String teachID) {
		this.teachID = teachID;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(String jsonResult) {
		this.jsonResult = jsonResult;
	}
}
